#ifndef PROCESSINGTHREAD_H
#define PROCESSINGTHREAD_H

#include <QObject>
#include <QTcpSocket>
#include <QJsonDocument>
#include <QCryptographicHash>
#include <QJsonObject>
#include <QDir>
#include <QDataStream>
#include <QThread>

#include "socket.h"

enum Type{
    INVALID = -1,
    UPDATE, //更新确认
    START, //文件开始
    DATA,
    FINISH,
    ERROR,
    VERSIONS_EXAMINE
};

struct FileData
{
    QString fileName;
    QString MD5;
    QByteArray fileContent;
    FileData()
        : fileName("")
        , MD5("")
        , fileContent("")
    {}
    bool operator == (const FileData& fd) const
    {
        if (fileName != fd.fileName) {
            return false;
        }
        if (MD5 != fd.MD5) {
            return false;
        }
        return true;
    }
};

struct TcpData
{
    Type type;
    QByteArray data;
};

struct name
{
    name() {}
};
class processingThread : public QObject
{
    Q_OBJECT
public:
    explicit processingThread(QTcpSocket* socket, int key);
public slots:
    void init();
    int getKey();
private slots:
    void onStateChanged(QAbstractSocket::SocketState socketState);
    void onSendUpdateRequest(); //更新开始
    void onReadyRead(QByteArray data);
    void onDisconnect(int num);
signals:
    void signalDisconnect(int num);
    void signalSendToClient(QByteArray data);
    void signalSocketInit();
private:
    template <typename T>
    QByteArray convertToByte(T v);
    /*结构体转换*/
    QByteArray convert(FileData fd);
    FileData convert(QByteArray data);
    /*传输封包*/
    QByteArray envelop(TcpData tData);
    TcpData unpack(QByteArray& data);
    /*获取MD5*/
    const QString countMd5(const QString filePath);
    /*获取目录所有文件*/
    const QStringList getDirAllFile(QString path);

    /*数据处理*/
    void datProcessing(TcpData tData);
    void startUpdate();
    void startTransfer(QString fileName = "");
    void finish(FileData tData);
    void sendFinish();
    void versionsExamine(FileData tData);
private:
    QStringList fileList; //可用结构体来保存数据更好，保存每个文件的数据 避免重复获取
    Socket* socketIo;
    QByteArray sourceData;
    int byteSize; //文件读取大小
    QTcpSocket* socket;
    int key;
    QString updatePath;
};

#endif // PROCESSINGTHREAD_H
